import {Component, OnInit, ViewEncapsulation, ViewChild} from '@angular/core';
import {ActivatedRoute, Params} from '@angular/router';
import {CommunityService} from '../community.service';
import {Subject} from 'rxjs/Subject';
import {SeedInfiniteScroll} from '@shared/components/infinite-scroll/seed-infinite-scroll/seed-infinite-scroll.component';
import {SeoService} from "@core/seo/seo.service";
import {CircleMembers, FeedRespVO, SocialCircleRespVO} from "@interface/index";
import {ToolsService} from "@shared/service/tools/tools.service";


@Component({
  selector: 'circle-detail',
  templateUrl: './circle-detail.component.html',
  styleUrls: ['./circle-detail.component.scss'],
  encapsulation: ViewEncapsulation.None,
})
export class CircleComponent implements OnInit {
  @ViewChild(SeedInfiniteScroll) infiniteScroll;
  public circle: SocialCircleRespVO;
  public members: Array<CircleMembers> = []; // 圈子会员
  public allFeeds: Array<FeedRespVO> = []; // 全部帖
  public latestFeeds: Array<FeedRespVO> = []; // 最新回复帖
  public primeFeeds: Array<FeedRespVO> = []; // 精华帖

  public stateStore = {
    haveDataTab: [true, true, true],
    loadOverTab: [false, false, false]
  };
  public dataStore = {
    tabPage: [1, 1, 1],
    noDataTab: [], // 没有数据
    noMoreDataTab: [], // 没有更多数据
    // switchedTab: [],
    delFeedId: null,
    memberTotal: null,
    // joinState: ''
  };
  public params = {
    circleId: null,
    page: 1,
    rows: 10,
    type: 0
  };

  public ngUnsubscribe: Subject<void> = new Subject<void>();

  constructor(private route: ActivatedRoute,
              private communityService: CommunityService,
              private _seoService: SeoService,
              private tools: ToolsService) {
    this.route.params.subscribe((params: Params) => {
      this.params.circleId = params['circleId'];
      this.getCircleDetailInfo(params['circleId']);
    });
  }

  /**
   * @description 查询圈子详情信息
   * @author ouyqx-691
   * @date 2017-12-12
   */
  getCircleDetailInfo(circleId: number) {
    this.communityService.getCircleDetailInfo(circleId).takeUntil(this.ngUnsubscribe).subscribe(res => {
      if (res.result === '0' && res.data) {
        this.circle = res.data;
        this.dataStore.memberTotal = res.data.members;
        this._seoService.setTKD(
          `${res.data.circleName}_求苗体育社区`,
          `${res.data.circleName}_运动社区,体育社区,论坛,体育圈`,
          `求苗社区以篮球,足球,NBA,网球,羽毛球,电竞娱乐,跑步话题为主，
          为拥有热情的体育爱好者们创造良好讨论氛围，提供个性化功能，加入兴趣圈子，参与社区讨论`
        );
      }
    });
  };

  // /**
  // * @description 查询圈子所有成员
  // * @author ouyqx-691
  // * @date 2017-12-12
  // */
  // getCircleMembers(circleId: number) {
  //   this.communityService.getCircleMembers(circleId).takeUntil(this.ngUnsubscribe).subscribe(res => {
  //     if (res.result === '0' && res.data) {
  //       this.members = res.data.list;
  //     }
  //   });
  // };

  /**
   * @description 获取 tab 索引
   * @author ouyqx-691
   * @date 2017-12-12
   */
  getTabIndex(tab) {
    const currentTab = tab.index + 1;
    // 当前 tab 重复点击不请求
    if (this.params.type !== currentTab) {
      this.params.type = currentTab; // 缓存当前 tab
      this.infiniteScroll.enable(true);
      this.getCircleFeed();
    }
  };

  /**
   * @description 查询圈子帖子
   * @author ouyqx-691
   * @date 2017-12-12
   */
  getCircleFeed() {
    const currentTab = this.params.type;
    //  没有数据tab、没有更多数据 tab 不再请求接口
    if (this.dataStore.noDataTab.indexOf(currentTab) !== -1
      || this.dataStore.noMoreDataTab.indexOf(currentTab) !== -1) {
      this.infiniteScroll.enable(false);
      return;
    }
    this.params.page = this.dataStore.tabPage[currentTab - 1];
    this.communityService.getCircleFeed(this.params).takeUntil(this.ngUnsubscribe).subscribe(res => {
      if (res.result === '0' && res.data) {
        const feeds = res.data.list;
        this.infiniteScroll.complete();
        this.dataStore.tabPage[currentTab - 1]++;

        // 无更多数据
        if (!res.data.hasNextPage) {
          this.infiniteScroll.enable(false);
          this.dataStore.noMoreDataTab.push(currentTab);
          // 没有数据
          if (feeds.length === 0) {
            this.dataStore.noDataTab.push(currentTab);
            this.stateStore.haveDataTab[currentTab - 1] = false;
            return;
          }
        }

        switch (currentTab) {
          case 1:
            this.allFeeds = this.allFeeds.concat(feeds);
            break;
          case 2:
            this.latestFeeds = this.latestFeeds.concat(feeds);
            break;
          case 3:
            this.primeFeeds = this.primeFeeds.concat(feeds);
            break;
        }
      }

    });
  };

  /**
   * @description 加入该圈子
   * @author ouyqx-691
   * @date 2017-12-12
   */
  handleCircle() {
    if (!this.circle.myJoin) {
      this.joinCircle();
    } else {
      this.quitCircle();
    }
  }

  /**
   * @description 加入该圈子
   * @author ouyqx-691
   * @date 2017-12-12
   */
  joinCircle() {
    const params = {
      id: this.params.circleId
    };
    this.communityService.joinCircle(params).takeUntil(this.ngUnsubscribe).subscribe(res => {
      if (res.result === '0' && res.data) {
        this.dataStore.memberTotal++;
        this.circle.myJoin = true;
        this.tools.showToast('加入成功');
      }
    });
  };

  /**
   * @description 退出圈子
   * @author ouyqx-691
   * @date 2017-12-15
   */
  quitCircle() {
    this.communityService.quitCircle(this.params.circleId).takeUntil(this.ngUnsubscribe).subscribe(res => {
      if (res.result === '0' && res.data) {
        this.dataStore.memberTotal--;
        this.circle.myJoin = false;
        this.tools.showToast('退出成功');
      }
    });
  }

  /**
   * @description 处理帖子
   * @author ouyqx-691
   * @date 2017-12-18
   */
  handleFeed(feedId: number) {
    this.dataStore.delFeedId = feedId;
    if (this.params.type === 1) {
      this.delFeed(this.allFeeds);
    } else if (this.params.type === 2) {
      this.delFeed(this.latestFeeds);
    } else {
      this.delFeed(this.primeFeeds);
    }
  }

  /**
   * @description 删除帖子
   * @author ouyqx-691
   * @date 2017-12-18
   */
  delFeed(feeds) {
    const feedId = this.dataStore.delFeedId;
    for (let i = 0; i < feeds.length; i++) {
      if (feedId === feeds[i].feedId) {
        feeds.splice(i, 1);
      }
    }
  }

  downloadAppTip(myCreate: boolean) {
    if (myCreate) {
      this.tools.presentConfirm('请下载App操作！');
    }
  }

  ngOnInit() {
  }
}

